package com.ctg.itrdc.imageconsole.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UrlValidFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest servletRequest = (HttpServletRequest)request;
		HttpServletResponse servletResponse = (HttpServletResponse)response;
		String path = servletRequest.getRequestURI();
		
		if(path.indexOf("/ctg-imageconsole-web/images") != -1 || path.indexOf("/ctg-imageconsole-web/dist") != -1) {
			chain.doFilter(servletRequest, servletResponse);
			return;
		}
		
		if(!isJsonRequest(servletRequest)) {
			if(path.indexOf("/ctg-imageconsole-web/dist") == -1){
//				servletResponse.sendRedirect("/ctg-imageconsole-web/dist/#/image_repository/list");
				servletResponse.sendRedirect("/ctg-imageconsole-web/dist/index.html#/overview");
				return;
			}
		}
		chain.doFilter(servletRequest, servletResponse);
	}
	
	/*
	 * 是否ajax请求，与页面直接输入地址区别开。
	 */
	private boolean  isJsonRequest(HttpServletRequest servletRequest){
		String accept = servletRequest.getHeader("Accept");  //包含application/json即是ajax请求。
		return accept.contains("application/json");
	}

	@Override
	public void destroy() {
		
	}

}
